<?php
/**
 * Created by PhpStorm.
 * User: wangjiangtao
 * Date: 2022/2/21
 * Time: 14:58
 */

namespace App\Console\Commands;
use App\Http\Model\Hint;
use App\Http\Model\PropEvent;
use App\Http\Model\PropLog;
use App\Http\Model\PropUserPack;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class SendPropByUuid extends Command{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Send:prop:by:uuid';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '批量赠送用户道具';

    protected $propEventModel = null;
    protected $propLogModel = null;
    protected $userPackModel = null;
    protected $propId = 672;
    protected $num = 1;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->propEventModel = new PropEvent();
        $this->propLogModel = new PropLog();
        $this->userPackModel = new PropUserPack();

    }

    public function handle(){
        set_time_limit(0);
        //获取待发放用户ids
        $txt = fopen(__DIR__ . '/../../../public/uuid.txt', "r");  //打开文件
        $uuids = [];
        $i=0;
        while( !feof($txt) )
        {
            $uuid = intval(fgets($txt));
            $uuids[$i]= $uuid;//fgets()函数从文件指针中读取一行
            $i++;
            if (count($uuids) > 900 ){
                $this->sendUuidsProp($uuids);
                $uuids = [];
                $i = 0;
            }

        }
        if ($uuids){
            $this->sendUuidsProp($uuids);
        }
        fclose($txt); // 关闭文件
        return '';

    }

    public function sendUuidsProp($uuids){
        $userIds = $this->getUserIds($uuids);
        foreach ($userIds as $userId){
            try{
                $this->grantProp($userId,$this->propId,$this->num);
                write_log('SendProp','success',$userId,$this->propId,$this->num);
            } catch (\Exception $e) {
                var_dump('发送失败: '.$userId);
                write_log('SendProp','error',$userId,$this->propId,$this->num);
                continue;
            }
        }

        return true;
    }

    public function getUserIds($uuids){
        $data = DB::table('user')
            ->whereIn('uuid',$uuids)
            ->get(['user_id']);
        $data = $this->objToArray($data);
        $userIds = array_column($data,'user_id');
        return $userIds;
    }


    //返回数组
    public function objToArray($document)
    {
        return json_decode(json_encode($document), true);
    }

    public function grantProp($userId,$propId,$num){
        // 查询道具
//        $getPropEventList = $this->propEventModel->getPropEventByPropId($propId);

        DB::beginTransaction();
        // 创建发放日志
        $propLogData = [
            "user_id" => $userId,
            "prop_id" => $propId,
            "suid" => 0,
            "type" => 3,
            "change" => $num
        ];
        $updateOrInsertPropLog = $this->propLogModel->updateOrInsertPropLog($propLogData);
        if (!$updateOrInsertPropLog) {
            DB::rollBack();
        }

        //放入用户背包 TODO 自动发送
        $grantResult = $this->putUserPack($userId,$propId, $num);
        if ($grantResult['code'] != Hint::SUCCESS) {
            extract($grantResult);
            DB::rollBack();
        }

        DB::commit();
        return '';
    }


    /**
     * 放入用户背包
     *
     * @param array $prop_id 道具
     * @param array $num 发放数量
     * @return array
     * */
    protected function putUserPack($user_id,$prop_id, $num)
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $inputType = 'insert';
            $params = [
                'user_id' => $user_id,
                'prop_id' => $prop_id,
//                'num' => $analysisPropEventData['value'],
                'num' => $num,
            ];

            // 检测用户背包道具是否存在
            $checkUserPack = $this->userPackModel->checkUserPack($user_id, $prop_id);
            if (!empty($checkUserPack)) {
                $inputType = 'increment';
                $params['user_pack_id'] = $checkUserPack['user_pack_id'];
            }

            // 创建/更新 用户背包
            $ret = $this->userPackModel->updateOrInsertUserPack($params, $inputType);
            if (!$ret) {
                $code = Hint::ERR_DATA_UPDATE_FAIL;
                $msg = '用户背包' . Hint::getErrCodeMsg($code);
                break;
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }


}
